package cn.wmingming.e3mall.sso.controller;

import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.utils.CookieUtils;
import cn.wmingming.common.utils.JsonUtils;
import cn.wmingming.e3mall.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Huangzm
 * @create 2018/06/22 18:15
 * @desc
 * @Modified By:
 **/
@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Value("${COOKIES_TOKEN}")
    private String COOKIES_TOKEN;


    @RequestMapping("/page/login")
    public String showLogin(String redirect,Model model )
    {
        model.addAttribute("redirect",redirect);
        return "login";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public E3Result login(String username, String password,HttpServletRequest request, HttpServletResponse response){
        E3Result result = userService.login(username, password);
        //登陆成功时，将token写进cookies
        if(result.getStatus() == 200){
            CookieUtils.setCookie(request,response,COOKIES_TOKEN, result.getData().toString());
        }
        return result;
    }

    @RequestMapping(value = "/user/token/{token}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String getUserByToken(@PathVariable String token, String callback){
        E3Result result = userService.getUserByToken(token);
        //如果callback不等于空,则要支持jsonp（json跨域请求,即返回js语句）
        if(StringUtils.isNoneBlank(callback))
            return callback+"("+JsonUtils.objectToJson(result)+")";

        return JsonUtils.objectToJson(result);
    }
}
